package com.tanhua.sso.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("user")
@RestController
public class UserController {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private UserService userService;

    /**
     * 校验登录
     * @param param
     * @return
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        String mobile = param.get("phone");
        String code = param.get("verificationCode");
        String token = userService.login(mobile, code);
        Map<String,Object> result = new HashMap<>();

        if (!StringUtils.isEmpty(token)) {
            String[] strings = token.split("\\|");
            boolean isNew = Boolean.parseBoolean(strings[0]);
            String tokenStr = strings[1];
            result.put("isNew",isNew);
            result.put("token",tokenStr);
            return ResponseEntity.ok(result);
        }

        ErrorResult.ErrorResultBuilder resultBuilder = ErrorResult.builder().errCode("000000").errMessage("登录失败");
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());
    }

    /**
     * 根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
